import configInfo, {
	env,
	tokenName
} from '../common/config.js'
import { logout } from '../common/action.js'

const api = ({
	url,
	data = {},
	method = 'GET',
	showLoading,
	loadingText = '请稍后'
}) => {
	return new Promise((ok, reject) => {
		uni.showNavigationBarLoading()
		if (showLoading) {
			uni.showLoading({
				title: loadingText,
				mask: true
			})
		}
		let app = getApp()
		const header = app.token ? {
				[tokenName]: app.token
			} : {}
			uni.request({
				url: configInfo.host + url,
				method,
				data,
				header,
				timeout: 5000,
				success: res => {
					uni.hideNavigationBarLoading()
					if (showLoading) {
						uni.hideLoading()
					}
					switch (res.statusCode){
						case 200:
							ok(res.data)
							break;
						case 401:
							logout()
							reject(res.data)
							break;
						case 403:
							uni.alert('您没有这个权限')
							reject(res.data)
							break;
						case 500:
							uni.alert(res.data.msg || "服务器未知错误")
							reject(res.data)
							break;
						default:
							uni.alert(res.data.msg || "网络状况不佳")
							reject(res.data)
							break;
					}
				}
			})
	})
}

export default api